import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_stort/resource/colors.dart';
import 'package:flutter_stort/utils/check_data_utils.dart';
import 'package:flutter_stort/utils/event_bus.dart';
import 'package:flutter_stort/utils/jump_util.dart';
import 'package:flutter_stort/utils/toast_utils.dart';

class RegisterPage extends StatefulWidget {
  @override
  _RegisterPageState createState() => _RegisterPageState();
}

class _RegisterPageState extends State<RegisterPage> {
  GlobalKey<FormState> _registerKey = GlobalKey();
  TextEditingController _mobileController = TextEditingController();
  TextEditingController _codeController = TextEditingController();
  TextEditingController _passwordController = TextEditingController();
  TextEditingController _confirmPasswordController = TextEditingController();

  bool _mobileVisibility = false;
  bool _codeVisibility = false;
  bool _passwordVisibility = false;
  bool _confirmPasswordVisibility = false;

  bool _pwdObscureText = true;
  bool _confirmPasswordObscureText = true;

  String _mobile;
  String _code;
  String _password;
  String _confirmPassword;

  ///获取验证码
  String _codeHint = "获取验证码";
  bool _isGetCode = true;
  int _seconds = 60;
  Timer _countdownTimer;

  ///初始化开始计时器
  void _startCountdown() {
    if (_countdownTimer != null) {
      return;
    }
    _countdownTimer = new Timer.periodic(Duration(seconds: 3), (timer) {
      setState(() {
        if (_seconds > 1) {
          _seconds--;
          _codeHint = "$_seconds s";
        } else {
          _codeHint = "获取验证码";
          _isGetCode = true;
        }
      });
    });
  }

  ///关闭定时器
  void _closeCountdown() {
    if (_countdownTimer != null) {
      _countdownTimer.cancel();
      _countdownTimer = null;
    }
  }

  @override
  void dispose() {
    _closeCountdown();
    super.dispose();
  }

  ///用户注册
  void _register() {
    _registerKey.currentState.save();
    if (checkData()) {
      EventBusUtils.eventBus
          .fire(EventUserEntity(mobile: _mobile, password: _password));
      JumpPageUtils.clostPage(context);
    }
  }

  ///获取验证码
  void _getCode() {
    _registerKey.currentState.save();
    if (checkMobile()) {
      _codeHint = "$_seconds s";
      _isGetCode = false;
      _startCountdown();
    }
  }

  bool checkMobile() {
    if (_mobile.isEmpty) {
      ToastUtil.showToast("请输入手机号码！");
      return false;
    }
    if (!CheckDataUtils.isPhone(_mobile)) {
      ToastUtil.showToast("您输入的手机号码格式不正确");
      return false;
    }
    return true;
  }

  ///数据校验
  bool checkData() {
    if (_mobile.isEmpty) {
      ToastUtil.showToast("请输入手机号码！");
      return false;
    }
    if (!CheckDataUtils.isPhone(_mobile)) {
      ToastUtil.showToast("您输入的手机号码格式不正确");
      return false;
    }
    if (_code.isEmpty) {
      ToastUtil.showToast("请输入验证码");
      return false;
    }
    if (_password.isEmpty) {
      ToastUtil.showToast("请输入密码！");
      return false;
    }
    if (_password.length < 3 || _password.length > 18) {
      ToastUtil.showToast("密码长度输入有误，长度在3-18位之间！");
      return false;
    }
    if (_confirmPassword.isEmpty) {
      ToastUtil.showToast("请输入密码！");
      return false;
    }
    if (_confirmPassword.length < 3 || _confirmPassword.length > 18) {
      ToastUtil.showToast("密码长度输入有误，长度在3-18位之间！");
      return false;
    }
    if (_password != _confirmPassword) {
      ToastUtil.showToast("两次输入的密码不一致，请重新输入");
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: CustomColor.titleColor,
        iconTheme: IconThemeData(
          color: Colors.white,
        ),
        title: Text(
          "注   册",
          style: TextStyle(
            fontSize: 22,
            color: Colors.white,
          ),
        ),
      ),
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.fromLTRB(10, 30, 10, 10),
          child: Form(
            key: _registerKey,
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Icon(Icons.phone_iphone),
                      Expanded(
                        flex: 1,
                        child: TextFormField(
                          keyboardType: TextInputType.number,
                          controller: _mobileController,
                          decoration: InputDecoration(
                            hintText: "请输入手机号码",
                            border: InputBorder.none,
                          ),
                          onSaved: (value) {
                            this._mobile = value;
                          },
                          onChanged: (value) {
                            setState(() {
                              if (value.length > 0) {
                                _mobileVisibility = true;
                              } else {
                                _mobileVisibility = false;
                              }
                            });
                          },
                          onEditingComplete: () {},
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          setState(() {
                            _mobileController.text = "";
                            _mobileVisibility = false;
                          });
                        },
                        child: Visibility(
                          visible: _mobileVisibility,
                          child: Container(
                            height: 50,
                            width: 40,
                            child: Icon(
                              Icons.close,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.grey,
                      width: 0.5,
                      style: BorderStyle.solid,
                    ),
                  ),
                ),
                SizedBox(
                  height: 20,
                ),
                Row(
                  children: [
                    Expanded(
                      child: Container(
                        padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                        height: 50,
                        child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            Icon(Icons.message),
                            SizedBox(
                              width: 10,
                            ),
                            Expanded(
                              flex: 1,
                              child: TextFormField(
                                keyboardType: TextInputType.number,
                                controller: _codeController,
                                decoration: InputDecoration(
                                  hintText: "请输入验证码",
                                  border: InputBorder.none,
                                ),
                                onSaved: (value) {
                                  this._code = value;
                                },
                                onChanged: (value) {
                                  setState(() {
                                    if (value.length > 0) {
                                      _codeVisibility = true;
                                    } else {
                                      _codeVisibility = false;
                                    }
                                  });
                                },
                                onEditingComplete: () {},
                              ),
                            ),
                            InkWell(
                              onTap: () {
                                setState(() {
                                  _codeController.text = "";
                                  _codeVisibility = false;
                                });
                              },
                              child: Visibility(
                                visible: _codeVisibility,
                                child: Container(
                                  height: 50,
                                  width: 40,
                                  child: Icon(
                                    Icons.close,
                                    color: Colors.grey,
                                  ),
                                ),
                              ),
                            ),
                          ],
                        ),
                        decoration: BoxDecoration(
                          border: Border.all(
                            color: Colors.grey,
                            width: 0.5,
                            style: BorderStyle.solid,
                          ),
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Container(
                      width: 140,
                      height: 50,
                      child: RaisedButton(
                        color: Colors.blue,
                        onPressed: _isGetCode ? _getCode : null,
                        disabledColor: Colors.grey,
                        child: Text(
                          _codeHint,
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 18,
                          ),
                        ),
                      ),
                    ),
                  ],
                ),
                SizedBox(
                  height: 20,
                ),
                Container(
                  padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Icon(Icons.lock),
                      Expanded(
                        flex: 1,
                        child: TextFormField(
                          keyboardType: TextInputType.visiblePassword,
                          obscureText: _pwdObscureText,
                          controller: _passwordController,
                          decoration: InputDecoration(
                            hintText: "请输入密码",
                            border: InputBorder.none,
                          ),
                          onSaved: (value) {
                            this._password = value;
                          },
                          onChanged: (value) {
                            setState(() {
                              if (value.length > 0) {
                                _passwordVisibility = true;
                              } else {
                                _passwordVisibility = false;
                              }
                            });
                          },
                          onEditingComplete: () {},
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          setState(() {
                            _passwordController.text = "";
                            _passwordVisibility = false;
                          });
                        },
                        child: Visibility(
                          visible: _passwordVisibility,
                          child: Container(
                            height: 50,
                            width: 40,
                            child: Icon(
                              Icons.close,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          setState(() {
                            if (_pwdObscureText) {
                              _pwdObscureText = false;
                            } else {
                              _pwdObscureText = true;
                            }
                          });
                        },
                        child: Container(
                          width: 40,
                          height: 50,
                          child: Icon(
                            _pwdObscureText
                                ? Icons.visibility
                                : Icons.visibility_off,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.grey,
                      width: 0.5,
                      style: BorderStyle.solid,
                    ),
                  ),
                ),
                SizedBox(height: 20),
                Container(
                  padding: EdgeInsets.fromLTRB(10, 0, 0, 0),
                  height: 50,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Icon(Icons.lock),
                      Expanded(
                        flex: 1,
                        child: TextFormField(
                          keyboardType: TextInputType.visiblePassword,
                          obscureText: _confirmPasswordObscureText,
                          controller: _confirmPasswordController,
                          decoration: InputDecoration(
                            hintText: "请输入确认密码",
                            border: InputBorder.none,
                          ),
                          onSaved: (value) {
                            this._confirmPassword = value;
                          },
                          onChanged: (value) {
                            setState(() {
                              if (value.length > 0) {
                                _confirmPasswordVisibility = true;
                              } else {
                                _confirmPasswordVisibility = false;
                              }
                            });
                          },
                          onEditingComplete: () {},
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          setState(() {
                            _confirmPasswordController.text = "";
                            _confirmPasswordVisibility = false;
                          });
                        },
                        child: Visibility(
                          visible: _confirmPasswordVisibility,
                          child: Container(
                            height: 50,
                            width: 40,
                            child: Icon(
                              Icons.close,
                              color: Colors.grey,
                            ),
                          ),
                        ),
                      ),
                      InkWell(
                        onTap: () {
                          setState(() {
                            if (_confirmPasswordObscureText) {
                              _confirmPasswordObscureText = false;
                            } else {
                              _confirmPasswordObscureText = true;
                            }
                          });
                        },
                        child: Container(
                          width: 40,
                          height: 50,
                          child: Icon(
                            _confirmPasswordObscureText
                                ? Icons.visibility
                                : Icons.visibility_off,
                            color: Colors.grey,
                          ),
                        ),
                      ),
                    ],
                  ),
                  decoration: BoxDecoration(
                    border: Border.all(
                      color: Colors.grey,
                      width: 0.5,
                      style: BorderStyle.solid,
                    ),
                  ),
                ),
                SizedBox(
                  height: 40,
                ),
                Container(
                  width: 400,
                  height: 50,
                  child: RaisedButton(
                    onPressed: _register,
                    color: Colors.blue,
                    shape: StadiumBorder(),
                    child: Text(
                      "注   册",
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 20,
                      ),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
